package com.example.demo.exception;

import lombok.Getter;
import org.springframework.http.HttpStatus;

/**
 * 自定义业务异常类
 */
@Getter
public class CustomException extends RuntimeException {
    private final HttpStatus httpStatus;
    private final String errorCode;
    private final String detail;

    // 基础构造方法
    public CustomException(String message, HttpStatus httpStatus) {
        this(message, httpStatus, "CUSTOM_ERROR", null);
    }

    // 完整构造方法
    public CustomException(String message, HttpStatus httpStatus, String errorCode, String detail) {
        super(message);
        this.httpStatus = httpStatus;
        this.errorCode = errorCode;
        this.detail = detail;
    }

    // 简化构造方法（默认500错误）
    public CustomException(String message) {
        this(message, HttpStatus.INTERNAL_SERVER_ERROR, "SYSTEM_ERROR", null);
    }

    // ============== 静态工厂方法 ==============

    public static CustomException unauthorized(String message) {
        return new CustomException(message, HttpStatus.UNAUTHORIZED, "AUTH_401", null);
    }

    public static CustomException forbidden(String message) {
        return new CustomException(message, HttpStatus.FORBIDDEN, "AUTH_403", null);
    }

    public static CustomException notFound(String resourceName) {
        return new CustomException(resourceName + "不存在", HttpStatus.NOT_FOUND, "RESOURCE_404", null);
    }

    public static CustomException badRequest(String message) {
        return new CustomException(message, HttpStatus.BAD_REQUEST, "PARAM_400", null);
    }

    public static CustomException conflict(String message) {
        return new CustomException(message, HttpStatus.CONFLICT, "DATA_409", null);
    }

    public static CustomException serviceUnavailable(String serviceName) {
        return new CustomException(serviceName + "服务不可用",
                HttpStatus.SERVICE_UNAVAILABLE, "SERVICE_503", null);
    }

    // 带详细信息的工厂方法
    public static CustomException badRequestWithDetail(String message, String detail) {
        return new CustomException(message, HttpStatus.BAD_REQUEST, "PARAM_400", detail);
    }
}